<script setup lang="ts">

import MyInput from "@/components/MyInput.vue";
import {nextTick, onActivated, onBeforeMount, onMounted, onUpdated, ref, watch} from "vue";
import MyTableColumn from "@/components/MyTableColumn.vue";
import {useAssetTypeApi, useAssetTypeProperty} from "@/apis/AssetTypeApi";
import {ElMessageBox} from "element-plus";

const emits = defineEmits(["save"])
const props = defineProps(["data"])
const model = defineModel()

const assetTypeApi = useAssetTypeApi()
const assetPropertyApi = useAssetTypeProperty()

let assetType = ref<any>({})

assetType.value = props.data

let ps = ref<Array<any>>([])

function loadProperty() {
  if (assetType.value.id){
    assetPropertyApi.list(assetType.value.id).then((res:any) => {
      ps.value = res
    })
  }else {
    console.log("AssetTypeId is null~~~~")
  }
}
const addProperty = () => {
  let nextIndex = ps.value.length
  const isExits = ps.value.some(item => item.isEdit)
  if (isExits){
    ElMessageBox.alert("请先保存编辑中的内容", "提示", {
      type: "warning"
    })
    return;
  }
  ps.value.push({
    text: "",
    isEdit: true,
    index: nextIndex
  })
}
const onSaveItem = (item:any) => {
  item.assetTypeId = assetType.value.id
  assetPropertyApi.save(item).then(() =>{
    loadProperty()
  })
}
const onDeleteItem = (item:any) => {
  assetPropertyApi.del(item.id).then(() => {
    loadProperty()
  })
}
const onCancel = (item:any) => {
  ps.value.splice(item.index, 1)
}
const onSaveAssetType = () => {
  assetTypeApi.save(assetType.value)
      .then((res => {
        emits("save")
      }))
}
const openChange = () => {
  assetType.value = props.data
  loadProperty()
}
</script>

<template>
  <el-drawer v-model="model" size="70%" @open="openChange">
    <el-form>
      <el-form-item label="资产类型">
        <el-input placeholder="资产类型名称" v-model="assetType.typeName"></el-input>
      </el-form-item>
      <el-form-item label="类型描述">
        <my-input label="添加" placeholder="类型描述" v-model="assetType.typeDesc"/>
      </el-form-item>
    </el-form>
    <el-divider content-position="left">属性</el-divider>
    <div class="m-table">
      <label>名称</label>
      <label>类型</label>
      <label>搜索</label>
      <label>列表</label>
      <label>操作</label>
    </div>
    <div v-for="item in ps">
      <my-table-column :data="item" key-name="id" @save="onSaveItem"
                       @delete="onDeleteItem" @cancel="onCancel" :key="item.id"/>
    </div>
    <div class="m-operate">
      <el-button link type="primary" @click="addProperty">添加</el-button>
    </div>
    <div class="btns">
      <el-button type="primary" @click="onSaveAssetType">保存</el-button>
    </div>
  </el-drawer>

</template>

<style scoped>
.m-table{
  display: flex;
  label{
    width: 20%;
    text-align: center;
    padding: 10px 0;
    font-size: 0.5em;
    border-bottom: 1px solid var(--el-border-color);
  }
}
.m-operate{
  padding: 5px 0;
}
.btns{
  padding: 10px 0;
  display: flex;
  justify-content: right;
}
</style>